package proxy

import (
	"context"
	"gin-gateway/example/gateway_demo/otherProxy/load_balance"
	"gin-gateway/example/gateway_demo/otherProxy/grpc_proxy"
	"google.golang.org/grpc"
	"log"
	"google.golang.org/grpc/credentials/insecure"
)

func NewGrpcLoadBalanceHandler(lb load_balance.LoadBalance) grpc.StreamHandler {
	return func() grpc.StreamHandler {
		nextAddr, err := lb.Get("") // 下游服务
		if err != nil {
			log.Fatal("get next addr fail")
		}
		director := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
			ClientConn, err := grpc.NewClient(nextAddr, grpc.WithTransportCredentials(insecure.NewCredentials()),
				grpc.WithDefaultCallOptions(grpc.ForceCodec(grpc_proxy.Codec())))
			return ctx, ClientConn, err
		}
		return grpc_proxy.TransparentHandler(director)
	}()
}
